package multiplus.base;

import java.sql.SQLException;
import java.util.Collection;
import java.util.Iterator;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.ibatis.sqlmap.client.SqlMapClient;

/**
 * ibatis 操作数据库基类
 * 
 * @author 李晓丹
 * 
 */
public abstract class BaseDao<E, PK> extends SqlMapClientDaoSupport implements
		IBaseDao<E, PK> {
	@Resource(name = "sqlMapClient")
	private SqlMapClient sqlMapClient;

	@Override
	public abstract String getNameSpace();

	@Override
	public String getSqlById(String id) {
		return this.getNameSpace().concat(".").concat(id);
	}

	@Override
	@PostConstruct
	public void initSqlMapClient() {
		super.setSqlMapClient(sqlMapClient);
	}

	@Override
	public E save(E entity) throws SQLException {
		return (E) sqlMapClient.insert(this.getSqlById("save"), entity);
	}

	@Override
	public int save(Collection<E> entities) throws SQLException {
		sqlMapClient.startBatch();
		Iterator<E> iterator = entities.iterator();
		while (iterator.hasNext()) {
			sqlMapClient.insert(this.getSqlById("insert"), iterator.next());
		}
		return sqlMapClient.executeBatch();
	}

	@Override
	public int delete(PK pk) throws SQLException {
		return sqlMapClient.delete(this.getSqlById("delete"), pk);
	}

	@Override
	public int update(E entity) throws SQLException {
		return sqlMapClient.update(this.getSqlById("update"), entity);
	}

	@Override
	public int update(Collection<E> entities) throws SQLException {
		sqlMapClient.startBatch();
		Iterator<E> iterator = entities.iterator();
		while (iterator.hasNext()) {
			sqlMapClient.update(this.getSqlById("update"), iterator.next());
		}
		return sqlMapClient.executeBatch();
	}

	@Override
	public E get(PK pk) throws SQLException {
		return (E) sqlMapClient.queryForObject(this.getSqlById("get"), pk);
	}
}
